package controller

import (
	"crypto/hmac"
	"crypto/sha1"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/sts"
	"github.com/e421083458/golang_common/lib"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"hash"
	"io"
	"tino_manager/dto"
	"tino_manager/middleware"
)

//OssController oss接口处理控制层
type OssController struct {
}

func OssRegister(group *gin.RouterGroup) {
	ossController := &OssController{}
	//获取sts临时凭证接口
	group.GET("/sts", ossController.STS)
}

type Policy struct {
	Expiration string          `json:"expiration"`
	Conditions [][]interface{} `json:"conditions"`
}

func (o *OssController) STS(c *gin.Context) {
	client, err := sts.NewClientWithAccessKey(lib.GetStringConf("base.oss.regionId"), lib.GetStringConf("base.oss.accessKeyId"), lib.GetStringConf("base.oss.accessKeySecret"))
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("获取上传权限失败"), true)
		return
	}
	request := sts.CreateAssumeRoleRequest()
	request.Scheme = "https"

	request.RoleArn = lib.GetStringConf("base.oss.roleArn")
	request.RoleSessionName = lib.GetStringConf("base.oss.RoleSessionName")
	response, err := client.AssumeRole(request)
	if err != nil {
		fmt.Println(err)
		middleware.ResponseError(c, 500, errors.New("获取上传权限失败"), true)
		return
	}
	//生成签名
	var policy Policy
	policy.Expiration = "9999-12-31T12:00:00.000Z"
	var conditions []interface{}
	conditions = append(conditions, "content-length-range")
	conditions = append(conditions, 0)
	conditions = append(conditions, 1048576000)
	policy.Conditions = append(policy.Conditions, conditions)
	policyByte, err := json.Marshal(policy)
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("获取上传权限失败"), true)
		return
	}
	policyBase64 := base64.StdEncoding.EncodeToString(policyByte)
	h := hmac.New(func() hash.Hash { return sha1.New() }, []byte(response.Credentials.AccessKeySecret))
	io.WriteString(h, policyBase64)
	signature := base64.StdEncoding.EncodeToString(h.Sum(nil))
	out := dto.OssStsOutput{
		SecurityToken:   response.Credentials.SecurityToken,
		AccessKeySecret: response.Credentials.AccessKeySecret,
		AccessKeyId:     response.Credentials.AccessKeyId,
		Policy:          policyBase64,
		Signature:       signature,
	}
	middleware.ResponseSuccess(c, out, false)
}
